<template>
  <div class="app-container calendar-list-container">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><span>{{$t('managementCost.buActualCost.queryCondition')}}</span></el-col>
      </el-row>
      <el-form :inline="true" :model="listQuery" style="padding: 0 20px">
        <el-row style="padding-bottom: 10px">
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Sales</div>
              <el-autocomplete style="width: 100%" clearable v-model="listQuery.name" :fetch-suggestions="getUserList" :placeholder="$t('managementCost.buActualCost.enterEmployeeNo')" @select="setUser"></el-autocomplete>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Account</div>
              <el-select clearable v-model="listQuery.bu" :placeholder="$t('placeholder.choose')">
                <el-option v-for="item in buList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('buBusiness.year')}}</div>
              <dict-select v-model="listQuery.year" code="year" clearable></dict-select>
            </div>
          </el-col>
          <el-col :span="4" style="margin-top: 33px">
            <div type="primary" class="yt-btn yt-btn-ys" @click="handleFilter">{{$t('button.query')}}</div>
            <div type="primary" class="yt-btn yt-ml8" @click="reset">{{$t('button.resetCondition')}}</div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="yt-data-list">
      <div class="yt-list-title">
        <span>Sales Target{{$t('managementCost.buActualCost.list')}}</span>
      </div>
      <div class="yt-list-content">
        <div class="list-operation">
          <div class="yt-btn yt-btn-ys" type="primary" @click="handleAdd">{{$t('button.new')}}</div>
          <div class="yt-btn yt-ml8" type="danger" @click="handleDelete">{{$t('button.delete')}}</div>
          <div class="yt-btn yt-ml8" type="danger" @click="handleEdit">{{$t('button.preserve')}}</div>
        </div>

        <el-table :data="list" :empty-text="$t('placeholder.emptyText')" border style="width: 100%;" class="yt-table  yt-temporary" @selection-change="handleSelectionChange" v-loading.body="listLoading" max-height="600">

          <el-table-column type="selection" align="center" prop="id" width="60"/>
          <el-table-column type="index" align="center" :label="$t('managementCost.buActualCost.serialNum')"/>
          <el-table-column align="center" :label="$t('buBusiness.year')" prop="year" >
            <template slot-scope="scope">
              <dict-select v-model="scope.row.year" code="year" ></dict-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Sales" prop="salesName" >
            <template slot-scope="scope">
              <el-autocomplete clearable v-model="scope.row.salesName" :fetch-suggestions="getUserList" :placeholder="$t('managementCost.buActualCost.enterEmployeeNo')" @select="item => setUserUpdate(scope.row,item)"></el-autocomplete>
            </template>
          </el-table-column>

          <el-table-column align="center" label="Account" prop="name">
              <template slot-scope="scope">
                <el-select v-model="scope.row.bu" @change="buChange(scope)" :placeholder="$t('placeholder.choose')">
                  <el-option v-for="item in buList" :value="item" :label="item" :key="item"></el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column align="center" label="Sales Target" width="120" prop="target">
              <template slot-scope="scope">
                <div>
                  <!--<el-input style="display: none" type="number" size="small" v-model="scope.row.target" disabled="true"></el-input>-->
                  <div v-format="'#,##0'" class="box">{{scope.row.target}}</div>
                </div>
              </template>
            </el-table-column>

          <el-table-column align="center" label="Q1" width="120" prop="target">
            <template slot-scope="scope">
              <div v-check-submit tabindex="0">
                <el-input style="display: none" type="number" size="small" v-model="scope.row.q1" @input="changeValue(scope.row)" :placeholder="$t('placeholder.content')"></el-input>
                <div v-format="'#,##0'" class="box" :placeholder="$t('placeholder.content')">{{scope.row.q1}}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="Q2" width="120" prop="target">
            <template slot-scope="scope">
              <div v-check-submit tabindex="0">
                <el-input style="display: none" type="number" size="small" v-model="scope.row.q2" @input="changeValue(scope.row)" :placeholder="$t('placeholder.content')"></el-input>
                <div v-format="'#,##0'" class="box" :placeholder="$t('placeholder.content')">{{scope.row.q2}}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="Q3" width="120" prop="target">
            <template slot-scope="scope">
              <div v-check-submit tabindex="0">
                <el-input style="display: none" type="number" size="small" v-model="scope.row.q3" @input="changeValue(scope.row)" :placeholder="$t('placeholder.content')"></el-input>
                <div v-format="'#,##0'" class="box" :placeholder="$t('placeholder.content')">{{scope.row.q3}}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="Q4" width="120" prop="target">
            <template slot-scope="scope">
              <div v-check-submit tabindex="0">
                <el-input style="display: none" type="number" size="small" v-model="scope.row.q4" @input="changeValue(scope.row)" :placeholder="$t('placeholder.content')"></el-input>
                <div v-format="'#,##0'" class="box" :placeholder="$t('placeholder.content')">{{scope.row.q4}}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" :label="$t('managementCost.buActualCost.updateName')" prop="updateName"/>

          <el-table-column align="center" :label="$t('managementCost.buActualCost.updateTime')" prop="updateTime" :formatter="formatter.formatTimes"/>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="listQuery.page"
            :page-sizes="[10, 20, 30, 50, 100, 200]"
            :page-size="listQuery.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!--新增弹窗-->
    <el-dialog :title="$t('button.new')" :visible.sync="dialogVisible" :before-close="dialogVisibleClose">

      <el-form ref="form" :model="Info" label-width="100px">
        <el-form-item :label="$t('buBusiness.year')" >
            <dict-select v-model="Info.year" code="year" clearable></dict-select>
        </el-form-item>
        <el-form-item label="Account">
          <el-select v-model="Info.bu" :placeholder="$t('placeholder.choose')">
            <el-option v-for="item in buList" :value="item" :label="item" :key="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Sales">
            <el-autocomplete style="width: 100%" clearable v-model="Info.name" :fetch-suggestions="getUserList" :placeholder="$t('managementCost.buActualCost.enterEmployeeNo')" @select="setUserInsert"></el-autocomplete>
        </el-form-item>
        <el-form-item label="Q1">
          <div v-check-submit tabindex="0">
            <el-input v-model="q1" @input="changeValueAdd" :placeholder="$t('placeholder.content')"></el-input>
            <div class="check_div box1" v-format="'#,##0'" :placeholder="$t('placeholder.content')">{{ q1 }}</div>
          </div>
        </el-form-item>
        <el-form-item label="Q2">
          <div v-check-submit tabindex="0">
            <el-input v-model="q2" @input="changeValueAdd" :placeholder="$t('placeholder.content')"></el-input>
            <div class="check_div box1" v-format="'#,##0'" :placeholder="$t('placeholder.content')">{{ q2 }}</div>
          </div>
        </el-form-item>
        <el-form-item label="Q3">
          <div v-check-submit tabindex="0">
            <el-input v-model="q3" @input="changeValueAdd" :placeholder="$t('placeholder.content')" ></el-input>
            <div class="check_div box1" v-format="'#,##0'" :placeholder="$t('placeholder.content')">{{ q3 }}</div>
          </div>
        </el-form-item>
        <el-form-item label="Q4">
          <div v-check-submit tabindex="0">
            <el-input v-model="q4"  @input="changeValueAdd" :placeholder="$t('placeholder.content')"></el-input>
            <div class="check_div box1" v-format="'#,##0'" :placeholder="$t('placeholder.content')">{{ q4 }}</div>
          </div>
        </el-form-item>
        <el-form-item label="Sales Target">
          <div>
            <el-input v-model="target" :disabled="true"></el-input>
            <div class="check_div box1" v-format="'#,##0'">{{ target }}</div>
          </div>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <div class="yt-btn yt-btn-ys" type="primary" @click="insertData">{{$t('button.preserve')}}</div>
        <div class="yt-btn yt-ml8" type="danger" @click="dialogVisibleClose">{{$t('button.cancel')}}</div>
    </span>
    </el-dialog>



  </div>
</template>

<script>
  import { selectBu, getBuInfo } from '@/api/bu/index';
  import dictSelect from '@/components/Dict/dictValueSelect';
  import { getUserInfoByName } from '@/api/dict/dictValue/index';
  import { getList, deleteData, insertData, updateData } from '@/api/pmoReport/salesTarget';
  import formatter from '@/utils/formatter';

  export default {
    name: 'buActualCost',
    data() {
      return {
        q1: '',
        q2: '',
        q3: '',
        q4: '',
        target: '',
        tableKey: 0,
        subtotal: {},
        formatter,
        listQuery: {
          page: 1,
          limit: 10,
          createBy: '',
          bu: ''
        },
        total: 0,
        list: [],
        selectionList: [],
        buList: [],
        dialogVisible: false,
        Info: {
          bu: '',
          name: '',
          q1: '',
          q2: '',
          q3: '',
          q4: '',
          salesId: '',
          salesName: '',
          target: '',
          year: ''
        },
        listLoading: true
      };
    },
    components: { dictSelect },
    created() {
      this.getQuery();
      this.getList();
      this.getBu()
    },
    methods: {
      changeValueAdd() {
        let target = 0
        if (this.q1) {
          target = Number.parseInt(this.q1) + target
        }
        if (this.q2) {
          target = Number.parseInt(this.q2) + target
        }
        if (this.q3) {
          target = Number.parseInt(this.q3) + target
        }
        if (this.q4) {
          target = Number.parseInt(this.q4) + target
        }
        this.target = target
        if (this.target !== 0) {
          let parts = this.target.toString()
          parts = parts.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
          this.target = parts
        }
      },
      changeValue(row) {
        let target = 0
        if (row.q1) {
          target = Number.parseInt(row.q1) + target
        }
        if (row.q2) {
          target = Number.parseInt(row.q2) + target
        }
        if (row.q3) {
          target = Number.parseInt(row.q3) + target
        }
        if (row.q4) {
          target = Number.parseInt(row.q4) + target
        }
        this.list[this.list.findIndex(item => item.id === row.id)].target = target
      },
      getQuery() {
        const buActualCostListQuery = window.sessionStorage.getItem('buActualCostListQuery');
        if (buActualCostListQuery) {
          this.listQuery = JSON.parse(buActualCostListQuery);
        }
      },
      insertData() {
        const list = [this.Info]
        const member = list[0]
        member.q1 = this.q1
        member.q2 = this.q2
        member.q3 = this.q3
        member.q4 = this.q4
        // 新增保存
        insertData([this.Info]).then(res => {
          this.$notify({
            title: res.status === 200 ? this.$t('tips.success') : this.$t('tips.fail'),
            message: res.status === 200 ? this.$t('tips.success') : res.message,
            type: res.status === 200 ? 'success' : 'warning'
          });
          if (res.status === 200) {
            this.dialogVisibleClose()
            this.getList();
            this.q1 = ''
            this.q2 = ''
            this.q3 = ''
            this.q4 = ''
          }
        });
      },
      dialogVisibleClose() {
        // 关闭弹窗
        this.dialogVisible = false
        this.Info = {}
        this.q1 = ''
        this.q2 = ''
        this.q3 = ''
        this.q4 = ''
      },
      buChange(scope) {
        getBuInfo({ bu: scope.row.bu }).then(res => {
          this.$set(this.list[scope.$index], 'bg', res.data.bg)
          this.$set(this.list[scope.$index], 'buType', res.data.buType)
          this.$set(this.list[scope.$index], 'country', res.data.country)
        });
      },
      getList() {
        this.listLoading = true;
        getList(this.listQuery).then(response => {
          if (response.data.rows && response.data.rows.length > 0) {
            this.list = response.data.rows;
          } else {
            this.list = [];
          }
          this.total = response.data.total;
          this.listLoading = false;
        });
      },
      handleAdd() {
        // 新增
        this.Info = {
          bu: '',
          name: '',
          q1: '',
          q2: '',
          q3: '',
          q4: '',
          salesId: '',
          salesName: '',
          target: '',
          year: ''
        }
        this.dialogVisible = true
      },
      handleDelete() {
        // 删除
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: this.$t('tips.fail'),
            message: this.$t('tips.pleaseChoose'),
            type: 'warning'
          });
          return;
        }
        deleteData(this.selectionList).then(res => {
          this.$notify({
            title: res.status === 200 ? this.$t('tips.success') : this.$t('tips.fail'),
            message: res.status === 200 ? this.$t('tips.success') : res.message,
            type: res.status === 200 ? 'success' : 'warning'
          });
          this.getList();
        });
      },
      handleEdit() {
        // 编辑
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: this.$t('tips.fail'),
            message: this.$t('tips.pleaseChoose'),
            type: 'warning'
          });
          return;
        }
        this.listLoading = true;
        updateData(this.selectionList).then(res => {
          this.listLoading = false;
          this.$notify({
            title: res.status === 200 ? this.$t('tips.success') : this.$t('tips.fail'),
            message: res.status === 200 ? this.$t('tips.success') : res.message,
            type: res.status === 200 ? 'success' : 'warning'
          });
          this.getList();
        });
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      handleSelectionChange(val) {
        //  表格序号选中函数
        this.selectionList = val;
      },
      handleFilter() {
        this.getList();
      },
      reset() {
        this.listQuery = { page: 1, limit: 10, salesId: '', bu: '' };
        this.getList();
      },
      getBu() {
        selectBu().then(res => {
          this.buList = res.data;
        });
      },
      getUserList(queryString, cb) {
        // 获取填写人信息
        getUserInfoByName({ username: queryString }).then(res => {
          this.userList = res.data.rows;
          for (let i = 0; i < this.userList.length; i++) {
            this.userList[i].value = this.userList[i].ename;
          }
          cb(this.userList);
        });
      },
      setUserInsert(item) {
        this.Info.salesId = item.id;
        this.Info.salesName = item.name;
      },
      setUserUpdate(scope, item) {
        scope.salesId = item.id
        scope.salesName = item.name;
        console.log(scope)
        console.log(item)
      },
      setUser(item) {
        this.listQuery.salesId = item.id;
      }
    },
    beforeDestroy() {
      window.sessionStorage.setItem('buActualCostListQuery', JSON.stringify(this.listQuery))
    }
  };
</script>
<style scoped>
  .check_div {
    height: 36px;
    width: 100%;
    line-height: 36px;
    background-color: rgb(255, 255, 255);
    border-radius: 4px;
    border: 1px solid rgb(220, 223, 230);
    box-sizing: border-box;
    outline: 0px;
    padding: 0px 30px !important;
    display: none;
  }
  .box{
    height: 36px;
    line-height: 36px;
    text-align: center;
    border-radius: 4px;
    color: #333;
    cursor:text;
    padding:0 15px;
  }
  .box:empty:before{
    content: attr(placeholder);
    color: #c0c4cc;
    font-size: 14px;
  }
  .box1{
    height: 36px;
    line-height: 36px;
    text-align: left;
    border-radius: 4px;
    color: #333;
    cursor:text;
    padding:0 15px !important;
  }
  .box1:empty:before{
    content: attr(placeholder);
    color: #c0c4cc;
    font-size: 12px;
  }
  .el-input.is-disabled /deep/ .el-input__inner {
    color: #333;
    cursor: not-allowed;
  }
</style>
